    <?php 

    # Supress notice
    @session_start();

    require 'conf.php';

    function login($username, $password)
    { 
        global $MW_host;
        $fields = array('USR_LOGIN' => '',
                        'USERNAME' => $username,
                        'PASSWD' => $password);

        $fields = http_build_query($fields);

        $h = curl_init($MW_host); 
        curl_setopt($h, CURLOPT_POST, 1);
        curl_setopt($h, CURLOPT_POSTFIELDS, $fields); 
        curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($h, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields))); 

    $res = curl_exec($h);
    
    if(!mb_check_encoding($res, 'UTF-8'))
        $res = utf8_encode($res);
    $data = json_decode($res);
    return $data;
}

function redirect_successful() 
{
    echo "<html><head><script>window.location = '/';</script></head></html>";
}

function redirect_with_message($msg)
{
    echo "<html><head><meta charset='utf-8'><script>alert('$msg'); window.location = '/';</script></head></html>";
}

header('Content-type: text/html; charset="utf-8"');

if (isset($_POST['username']) && isset($_POST['password'])) {

    # Prevents the middleware from barfing
    if ($_POST['username'] == '') {
        $_POST['username'] == 'a';
    }

    if ($_POST['password'] == '') {
        $_POST['password'] == 'a';
    }

    $session = login($_POST['username'], $_POST['password']);
    if ($session === null) {
        redirect_with_message("Ett fel uppstod i komunikationen med mellan-servern");
        exit();
    } else if (isset($session->session)) {
        $_SESSION['username'] = $_POST['username'];
        $_SESSION['sessiontoken'] = $session->session;
        $_SESSION['name'] = $session->name;
        $_SESSION['greet'] = $session->greet;

        redirect_successful();

    } else if (isset($session->error)) {
        redirect_with_message($session->error);
    } else {
        redirect_with_message("Servern är nere. Försöker igen..");
    }
} else if (!isset($_SESSION['sessiontoken'])) {
    $session = login('default', 'pass1');
    if (isset($session->session)) {
        $_SESSION['username'] = 'default';
        $_SESSION['sessiontoken'] = $session->session;
        $_SESSION['name'] = $session->name;
        $_SESSION['greet'] = $session->greet;
        
        redirect_successful();

    } else if (isset($session->error)) {
        redirect_with_message($session->error);
    } else {
        redirect_with_message("Servern är nere. Försöker igen..");
    }
}    

?>
